import { getYMD, getNowFormatDate, getDay, compareObject, formatGMTDate, unique } from '../../../../assets/js/util.js'

import echarts from 'echarts'
import advance from './advancedFilter.vue'

export default {
    data() {
        return {
            title: '分渠道概况',
            xlsxTitle: "",
            xlsxTitleQ: '',
            // 默认参数 和 URL
            SRC: '',
            DP: {
                p: '',
                f: ''
            },
            nowDate: getNowFormatDate(),
            date: "",
            dateArr: [],
            loading: false,
            loading2: false,
            searchable: true,
            chooseable: true,
            platform: 'all',
            timers: '',
            quota: '', //指标
            quotas: [], //指标
            channel: ['203', '83', '202'],
            channel1: ['203', '83', '202'],
            channels: [],
            delivery: false, //switch全选按钮
            delivery2: false, //switch全选按钮
            deliveryChange: false, //switch全选按钮
            dialogFormVisible: false,
            activeIndex: 0, //平台index
            pickerOptions: {
                disabledDate(time) {
                    if (time.getTime() < Date.now() - (8.64e7 * 7) || time.getTime() > Date.now()) {
                        return time.getTime();
                    }
                }
            },
            // 筛选渠道
            filterChannel: [],
            formLabelWidth: '100px',
            platformDatas: [], //整体数据
            retlist: [],
            retlists: [], //分渠道表
            retlistsCp: [], //分渠道数据拷贝
            channelHourDatas: [], //分小时表
            channelHourData: [],
            /*realTimeServiceContent 的宽*/
            realTimeServiceContent: '100%',
            /*表的宽度*/
            realTimeServiceTableWidth: "100%",
            /*渠道分小时数据数据表头*/
            platListTabelHead: [
                { prop: '1', label: '00:00~00:59' },
                { prop: '2', label: '01:00~01:59' },
                { prop: '3', label: '02:00~02:59' },
                { prop: '4', label: '03:00~03:59' },
                { prop: '5', label: '04:00~04:59' },
                { prop: '6', label: '05:00~05:59' },
                { prop: '7', label: '06:00~06:59' },
                { prop: '8', label: '07:00~09:59' },
                { prop: '9', label: '08:00~08:59' },
                { prop: '10', label: '09:00~09:59' },
                { prop: '11', label: '10:00~10:59' },
                { prop: '12', label: '11:00~11:59' },
                { prop: '13', label: '12:00~12:59' },
                { prop: '14', label: '13:00~13:59' },
                { prop: '15', label: '14:00~14:59' },
                { prop: '16', label: '15:00~15:59' },
                { prop: '17', label: '16:00~16:59' },
                { prop: '18', label: '17:00~17:59' },
                { prop: '19', label: '18:00~18:59' },
                { prop: '20', label: '19:00~10:59' },
                { prop: '21', label: '20:00~20:59' },
                { prop: '22', label: '21:00~21:59' },
                { prop: '23', label: '22:00~22:59' },
                { prop: '24', label: '23:00~23:59' }
            ],
            allTabelHead: [],
            channelTabelHead: [

            ],
            channelHourDatasHead: [],
            /*当前页显示数量*/
            pageSize1: 10,
            /*每页显示的数量*/
            pageSizes1: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal1: 0,
            /*分页器*/
            currentPage1: 1,

            /*当前页显示数量*/
            pageSize2: 10,
            /*每页显示的数量*/
            pageSizes2: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal2: 0,
            /*分页器*/
            currentPage2: 1
        }
    },
    computed: {
        // xlsx() {
        //     return this.title + '.xlsx'
        // }
    },
    methods: {
        successFun(data) {
            this.$message({
                message: data,
                type: 'success'
            });
        },
        errorFun(data) {
            this.$message.error(data);
        },
        // 表格1 的表头
        tableHeaderFun() {
            this.allTabelHead = [
                { prop: 'platformid', label: '平台名称', width: '160px', sortable: true, fixed: false },
                { prop: 'activate', label: '激活设备', width: '160px', sortable: true, fixed: false },
                { prop: 'newDevice', label: '新增设备', width: '160px', sortable: true, fixed: false },
                { prop: 'newUser', label: '新增帐号', width: '160px', sortable: true, fixed: false },
                { prop: 'activeUser', label: '活跃帐号', width: '160px', sortable: true, fixed: false },
                { prop: 'payUser', label: '付费帐号', width: '160px', sortable: true, fixed: false },
                { prop: 'pay', label: "付费金额(" + localStorage.getItem("ZULONGBICURRENCY") + ")", width: '160px', sortable: true, fixed: false },
                { prop: 'payUserInActiveRadio', label: '活跃付费率', width: '160px', sortable: true, fixed: false },
                { prop: 'payARPU', label: "付费ARPU(" + localStorage.getItem("ZULONGBICURRENCY") + ")", width: '160px', sortable: true, fixed: false },
                { prop: 'activeARPU', label: "活跃ARPU(" + localStorage.getItem("ZULONGBICURRENCY") + ")", width: '160px', sortable: true, fixed: false },
                { prop: "the2LeftRadio", label: `${this.dateArr[0]}-用户次日留存率`, width: '160px', sortable: true, fixed: false },
                { prop: "the3LeftRadio", label: `${this.dateArr[1]}-用户3日留存率`, width: '160px', sortable: true, fixed: false },
                { prop: "the7LeftRadio", label: `${this.dateArr[2]}-用户7日留存率`, width: '160px', sortable: true, fixed: false },
                { prop: 'the2MacLeftRadio', label: `${this.dateArr[0]}-mac次日留存率`, width: '160px', sortable: true, fixed: false },
                { prop: 'the3MacLeftRadio', label: `${this.dateArr[1]}-mac3日留存率`, width: '160px', sortable: true, fixed: false },
                { prop: 'the7MacLeftRadio', label: `${this.dateArr[2]}-mac7日留存率`, width: '160px', sortable: true, fixed: false }
            ];
            this.channelTabelHead = [
                { prop: 'channelid', label: '渠道名称', width: '160px', sortable: true },
                { prop: 'activate', label: '激活设备', width: '160px', sortable: true },
                { prop: 'newDevice', label: '新增设备', width: '160px', sortable: true },
                { prop: 'newActRate', label: '新增激活转化率', width: '160px', sortable: true },
                { prop: 'newUser', label: '新增帐号', width: '160px', sortable: true },
                { prop: 'activeUser', label: '活跃帐号', width: '160px', sortable: true },
                { prop: 'payUser', label: '付费帐号', width: '160px', sortable: true },
                { prop: 'pay', label: "付费金额(" + localStorage.getItem("ZULONGBICURRENCY") + ")", width: '160px', sortable: true },
                { prop: 'payUserInActiveRadio', label: '活跃付费率', width: '160px', sortable: true },
                { prop: 'payARPU', label: "付费ARPU(" + localStorage.getItem("ZULONGBICURRENCY") + ")", width: '160px', sortable: true },
                { prop: 'activeARPU', label: "活跃ARPU(" + localStorage.getItem("ZULONGBICURRENCY") + ")", width: '160px', sortable: true },
                { prop: "the2LeftRadio", label: `${this.dateArr[0]}-用户次日留存率`, width: '160px', sortable: true },
                { prop: "the3LeftRadio", label: `${this.dateArr[1]}-用户3日留存率`, width: '160px', sortable: true },
                { prop: "the7LeftRadio", label: `${this.dateArr[2]}-用户7日留存率`, width: '160px', sortable: true },
                { prop: 'the2MacLeftRadio', label: `${this.dateArr[0]}-mac次日留存率`, width: '160px', sortable: true },
                { prop: 'the3MacLeftRadio', label: `${this.dateArr[1]}-mac3日留存率`, width: '160px', sortable: true },
                { prop: 'the7MacLeftRadio', label: `${this.dateArr[2]}-mac7日留存率`, width: '160px', sortable: true }
            ]
        },
        dateChange(val) {
            this.date = val;
            this.dateArr = [
                formatGMTDate(new Date(val) - 86400000 * 1, true),
                formatGMTDate(new Date(val) - 86400000 * 2, true),
                formatGMTDate(new Date(val) - 86400000 * 6, true),
            ]
            this.tableHeaderFun();
        },
        // 分页器
        // 控制每页的数量
        handleSizeChange1(val) {
            this.pageSize1 = val;
            this.tableControl1();
        },
        // 页数
        handleCurrentChange1(val) {
            this.currentPage1 = val;
            this.tableControl1();
        },
        tableControl1() {
            this.retlist = [];
            this.retlist = this.retlists.slice((this.currentPage1 - 1) * this.pageSize1, this.currentPage1 * this.pageSize1)
        },
        // 分页器
        // 控制每页的数量
        handleSizeChange2(val) {
            this.pageSize2 = val;
            this.tableControl2();
        },
        // 页数
        handleCurrentChange2(val) {
            this.currentPage2 = val;
            this.tableControl2();
        },
        tableControl2() {
            this.channelHourData = []
            this.channelHourData = this.channelHourDatas.slice((this.currentPage2 - 1) * this.pageSize2, this.currentPage2 * this.pageSize2)
        },
        loads() {
            this.loading = !this.loading; //加载中
            this.searchable = !this.searchable; //查询按钮不可用
        },
        quotasChange(val) {
            this.quota = val
            this.getData(this.date, this.platform, this.quota, '202')
            this.loads()
        },
        //查询按钮
        search(form) {
            if (this.date == undefined || this.date.length < 0) {
                this.errorFun('请完善输入的值！');
                this.date = getNowFormatDate()
                return false;
            } else {
                this.getData(this.date, this.platform, this.quota, '202');
                this.loads()
                this.loading2 = true;
                this.chooseable = true
                this.sure();
            }
        },
        // 表格下载
        excel(tabelHead, data, val, id) {


            var that = this;
            if (id == 2) {
                if (that.activeIndex == 0) {
                    that.xlsxTitle = val + "-全平台-" + that.date;
                } else if (that.activeIndex == 1) {
                    that.xlsxTitle = val + "-ios-" + that.date;
                } else if (that.activeIndex == 2) {
                    that.xlsxTitle = val + "-ios越狱-" + that.date;
                } else if (that.activeIndex == 3) {
                    that.xlsxTitle = val + "-安卓-" + that.date;
                }
            } else if (id == 3) {
                if (that.quota == "newUser") {
                    that.xlsxTitle = val + "-新增账号数-" + that.date;
                } else if (that.quota == "payUser") {
                    that.xlsxTitle = val + "-付费账号数-" + that.date;
                } else if (that.quota == "pay") {
                    that.xlsxTitle = val + "-付费金额-" + that.date;
                } else if (that.quota == "newPayUser") {
                    that.xlsxTitle = val + "-新增账号付费人数-" + that.date;
                } else if (that.quota == "newPay") {
                    that.xlsxTitle = val + "-新增账号付费金额-" + that.date;
                }
            } else {
                that.xlsxTitle = val + "-" + that.date;
            }
            that.downloadExl(tabelHead, data, that.xlsxTitle, val);
        },
        initData() {
            this.$http.jsonp(`${this.SRC}data/get.do`, {
                params: {
                    p: this.DP.p,
                    f: this.DP.f,
                    a: "initParam",
                    ps: ""
                }
            }).then(function(res) {
                var data = JSON.parse(JSON.parse(res.body));
                // console.log(data)
                if (parseInt(data['res']) === 0) {
                    // console.log(data)
                    // this.platformDatas = data.platformDatas
                    if (data.allZhiBiaoItmes != undefined) {
                        for (var i in data.allZhiBiaoItmes) {
                            this.quotas.push({ label: i, value: data.allZhiBiaoItmes[i] })
                        }
                        this.quota = this.quotas[0].value;
                        // console.log(this.quotas)
                    }
                    if (data.channelItmes != undefined) {
                        for (var i in data.channelItmes) {
                            this.channels.push({ label: i, value: data.channelItmes[i] })
                                // console.log(data.channelItmes[i])
                                // this.channel.push(data.channelItmes[i])
                        }
                        this.loading2 = true;
                        this.chooseable = true
                        this.sure();
                    }
                } else {
                    this.getErrorMsg(Number(data.res))
                }
            })
        },
        getChannelData(index, plat) {
            //console.log(index);
            this.activeIndex = index;
            this.platform = plat;
            this.getData(this.date, this.platform, this.quota, this.channel)
            this.loads()
        },
        /*获取数据*/
        getData(date, plat, zhibiao, channel) {
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=search`, {
                params: { 'ps': `date=${date}&selectedPlatform=${plat}&selectZhiBiaoItem=${zhibiao}&channelItmes=${channel}` }
            }).then(function(res) {
                var data = JSON.parse(res.body);
                for (var i = 0; i < 24; i++) {
                    data = data.replace(eval('/\,' + i + '\:/g'), '\,\"' + i + '\"\:').replace(eval('/\{' + i + '\:/g'), '\{\"' + i + '\"\:').replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}')
                }
                data = JSON.parse(data);
                this.loading = false; //加载中
                this.searchable = false; //查询按钮不可用
                if (parseInt(data['res']) === 0) {
                    if (data.platformDatas.length == 0) {
                        this.errorFun('暂无数据！')
                        return;
                    }
                    if (data.platformDatas.length > 0) {
                        data.allPlatformData.platformid = '全平台'
                        data.platformDatas.push(data.allPlatformData)
                        this.platformDatas = [];
                        this.platformDatas = this.platformData(data.platformDatas);
                        this.platformDatas.sort(compareObject('activeUser', false));
                    }
                    if (data.retlist.length > 0) {
                        this.retlists = [];
                        this.retlists = this.platformData(data.retlist);
                        this.retlistsCp = this.retlists;
                        this.retlists.sort(compareObject('activeUser', false));
                        this.filterChannel = [];
                        for (var n = 0; n < this.retlists.length; n++) {
                            var obj = {
                                label: n,
                                value: this.retlists[n].channelid
                            }
                            this.filterChannel.push(obj)
                        }
                        this.dataTotal1 = this.retlists.length;
                        this.tableControl1()
                    }
                    if (data.channelHourDatas.length > 0) {
                        var arr = [];
                        this.channelHourDatas = [];
                        for (var i = 0, len = data.channelHourDatas.length; i < len; i++) {
                            data.channelHourDatas[i].datas.channelid = data.channelHourDatas[i].channelid;
                            this.channelHourDatas.push(data.channelHourDatas[i].datas)
                            for (var j in data.channelHourDatas[i].datas) {
                                if (j !== 'channelid') {
                                    if (data.channelHourDatas[i].datas[j] === '') {
                                        data.channelHourDatas[i].datas[j] = 0;
                                    } else {
                                        data.channelHourDatas[i].datas[j] = parseInt(data.channelHourDatas[i].datas[j]);
                                    }
                                }
                            }
                        }
                        this.dataTotal2 = this.channelHourDatas.length;
                        this.tableControl2()
                        this.channelHourDatasHead = [];
                        for (var j in data.channelHourDatas[0].datas) {
                            var temp = '';
                            if (Number(j) >= 0) {
                                if (Number(j) < 10) {
                                    temp = '0' + j.toString() + ':00~0' + j.toString() + ':59';
                                } else {
                                    temp = j.toString() + ':00~' + j.toString() + ':59';
                                }
                            }
                            var obj = { prop: j, label: temp, fixed: false };
                            this.channelHourDatasHead.unshift(obj);
                        }
                        for (var k in this.channelHourDatasHead) {
                            if (this.channelHourDatasHead[k]['prop'] == "channelid") {
                                this.channelHourDatasHead[k]['label'] = '渠道名称';
                                this.channelHourDatasHead[k]['fixed'] = true;
                            }
                        }
                    }
                } else {
                    this.errorFun(data['msg'])
                }
            })
        },
        //小数变成百分数
        dataFormat(val, id) {
            if (val == 0 && id != 1) {
                val = "";
                return val;
            } else {
                var temp = val * 100
                val = temp.toString().substring(0, 5) + '%'
                return val;
            }
        },
        platformData(arr) { //渲染platformData
            for (var i = 0, len = arr.length; i < len; i++) {
                arr[i].payUserInActiveRadio = this.dataFormat(arr[i].payUserInActiveRadio, 1)
                arr[i].the2LeftRadio = this.dataFormat(arr[i].the2LeftRadio)
                arr[i].newActRate = this.dataFormat(arr[i].newActRate)
                arr[i].the3LeftRadio = this.dataFormat(arr[i].the3LeftRadio)
                arr[i].the7LeftRadio = this.dataFormat(arr[i].the7LeftRadio)
                arr[i].the2MacLeftRadio = this.dataFormat(arr[i].the2MacLeftRadio)
                arr[i].the3MacLeftRadio = this.dataFormat(arr[i].the3MacLeftRadio)
                arr[i].the7MacLeftRadio = this.dataFormat(arr[i].the7MacLeftRadio)
            }
            return arr;
        },
        servList(data) { //渲染servList
            var temp1 = this._pushData(data.chanList[0]);
            this.servLists.push(temp1)
            for (var i = 1, len = data.servList.length; i < len; i++) {
                var temp2 = this._pushData(data.servList[i]);
                this.servLists.push(temp2)
            }
            this.dataTotal2 = this.servLists.length;

        },
        _pushData(arr) {
            var obj = {}
            for (var i = 0, len = arr.length; i < len; i++) {
                obj[i] = arr[i]
            }
            return obj
        },
        /*设置初始值*/
        _init() {
            window.addEventListener('resize', function() {
                /*修改表格的宽度*/
                this.realTimeServiceTableWidth = document.body.clientWidth - 240 + "px";
                this.realTimeServiceContent = document.body.clientWidth - 220 + "px";
                this.realTimeDataChart.resize()
            }.bind(this))

        },
        //全选/全不选  操作
        allChannels() {
            // console.log(this.delivery)
            if (this.delivery) {
                this.channel = []
                for (var i = 0, len = this.channels.length; i < len; i++) {
                    this.channel.push(this.channels[i].value)
                }
            } else {
                this.channel = []
            }
            // console.log(this.deliveryChange,this.channel1)
        },
        //在点击多选按钮时判断全选开关
        groupChange(val) {
            // console.log(this.channel.length, this.channels.length)
            if (this.channel.length != this.channels.length) {
                this.delivery = false;
            } else {
                this.delivery = true;
            }
        },
        //确定按钮
        sure1() {
            this.loading2 = true;
            this.chooseable = true
                // this.yes = true;
                // this.delivery=true;
            this.channel1 = this.channel;
            this.sure();
            this.timer();
        },
        //获取图表数据
        sure() {
            this.dialogFormVisible = false;
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=updateRealtimeChartData`, {
                params: { 'ps': `date=${this.date}&channelItmes=${this.channel1}` }
            }).then(function(res) {
                var data = JSON.parse(res.body);
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'))
                    // console.log(data)
                if (parseInt(data["res"]) === 0) {
                    // that.detailsSort(data["datas"]);
                    this.echartsData(data.channelOnlineRealTimeChart.jsonStr);
                    this.loading2 = false;
                    this.chooseable = false;
                } else {
                    this.errorFun(data['msg']);
                }
            })

        },
        //取消按钮
        cancel() {
            this.dialogFormVisible = false
            this.delivery = this.delivery2
            this.channel = [];
            this.channel = this.channel1;
            // this.yes = false;
            this.timer();
        },
        //记录打开时开关的状态，方便点取消时还原
        showGroup() {
            this.dialogFormVisible = true
            this.delivery2 = this.delivery;
            clearInterval(this.timers)
        },
        echartsData(datas) {
            var serie = [];
            for (var i = 0; i < datas.data.length; i++) {
                var item = {
                    name: datas.names[i],
                    data: datas.data[i],
                    type: 'line'
                }
                serie.push(item);
            };
            // console.log(serie)
            this.setOpt(datas, serie)
        },
        setOpt(datas, val) {
            // console.log(val)
            this.realTimeDataChart.setOption({
                series: val,
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    top: '14px',
                    width: '70%',
                    data: datas.names
                },
                grid: {
                    left: '0%',
                    right: '1%',
                    bottom: '15%',
                    containLabel: true
                },
                toolbox: {
                    right: '20',
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {
                            type: ['line', 'bar']
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: datas.columnkeys,
                    axisLabel: {
                        interval: 10,
                        rotate: 45, //倾斜度 -90 至 90 默认为0  
                        margin: 20,
                    },
                },
                yAxis: {
                    type: 'value',
                    // max: 10000
                },
                dataZoom: [{
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }]
            }, true);
        },
        timer() {
            var that = this;
            this.timers = setInterval(() => {
                if (that.$route.path === '/main/realTime/realTimeChannel') {
                    this.sure();
                    this.getData(this.date, this.platform, this.quota, '202');
                    this.nowDate = getNowFormatDate();
                }
            }, 15000)
        },
        // 表格排序
        sortChange(column) {
            if (column.prop === null) {
                return;
            } else if (column.order === 'descending') {
                this.retlists.sort(compareObject(column.prop, false));
            } else { //正序
                this.retlists.sort(compareObject(column.prop, true));
            }
            this.tableControl1();
        },
        // 表格排序
        sortChange2(column) {
            if (column.prop === null) {
                return;
            } else if (column.order === 'descending') {
                this.channelHourDatas.sort(compareObject(column.prop, false));
            } else { //正序
                this.channelHourDatas.sort(compareObject(column.prop, true));
            }
            this.tableControl2();
        },
        // 筛选表格中的数据
        filterFun(value) {
            if (value.length === 0) {
                this.retlists = this.retlistsCp;
            } else {
                var arr = [];
                for (var i = 0; i < this.retlists.length; i++) {
                    for (var j = 0; j < value.length; j++) {
                        if (this.retlists[i].channelid === value[j]) {
                            arr.push(this.retlists[i])
                        }
                    }
                }
                this.retlists = arr;
            }
            this.tableControl1();
            this.dataTotal1 = this.retlists.length;
        }
    },
    components: {
        'v-advance': advance,
    },
    mounted() {
        // 初始化URL
        this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
        this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
        this.date = formatGMTDate(new Date(), true);
        this.dateArr = [formatGMTDate(new Date() - 86400000 * 1, true), formatGMTDate(new Date() - 86400000 * 2, true), formatGMTDate(new Date() - 86400000 * 6, true)];
        this.tableHeaderFun();
        this.initData();
        this.realTimeDataChart = echarts.init(document.querySelector('.realTimeData'));
        this.getData(this.date, this.platform, 'newUser', '202')
            // this.loads()
        this._init();
        setTimeout(this.timer(), 15000);
    },
    beforeCreate() {
        this.currency = localStorage.getItem('ZULONGBICURRENCY');
    }
}